package com.livgo.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.livgo.dao.po.FileInfo;
import com.livgo.service.FileService;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class FiledDeleteTask {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileStorageService fileStorageService;

    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteFile() {

        LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<>();

        LocalDateTime ago = LocalDateTime.now().minusDays(31);

        queryWrapper.ge(FileInfo::getExpireTime, ago)
                .eq(FileInfo::getType, 0)
                .or()
                .eq(FileInfo::getType, 1);

        List<FileInfo> list = fileService.list(queryWrapper);

        org.dromara.x.file.storage.core.FileInfo fileInfo = new org.dromara.x.file.storage.core.FileInfo();

        list.forEach(info -> {
            LocalDateTime thirty = LocalDateTime.now().minusDays(30);
            LocalDateTime seven = LocalDateTime.now().minusDays(7);

            fileInfo.setPlatform("webdav-1")
                    .setBasePath("webdav/")
                    .setPath(info.getUri())
                    .setFilename(info.getFileName());

            if (info.getType() == 0 && info.getUploadTime().isBefore(thirty)) {
                fileStorageService.delete(fileInfo);
                fileService.removeById(info.getId());
            }
            if (info.getType() == 1 &&
                    (info.getExpireTime().isBefore(LocalDateTime.now()))
                    || info.getUploadTime().isBefore(seven)) {
                fileStorageService.delete(fileInfo);
                fileService.removeById(info.getId());
            }
        });

    }

}
